package com.wsjc.common.core.annotation.datasource;



import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by IDEA
 * User: agui
 * Date: 2017-04-01 13:35
 * Desc: 定义选择数据源切面
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    private static final Logger logger = Logger.getLogger(DynamicDataSourceAspect.class);

    
    /**
	 * service层切点 注解拦截
	 */
	@Pointcut("execution(* com.wsjc.manager.service.rpc.data..*(..))")
	public void aspect() {}
    
	@Before("aspect()")
	public void doBefore(JoinPoint point) throws InterruptedException {
		 Object target = point.getTarget();
	        String methodName = point.getSignature().getName();
	        Class<?>[] clazz = target.getClass().getInterfaces();
	        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
	        try {
	            Method method = clazz[0].getMethod(methodName, parameterTypes);
	            if (method != null && method.isAnnotationPresent(DataSource.class)) {
	                DataSource data = method.getAnnotation(DataSource.class);
	                DynamicDataSourceHolder.putDataSource(data.value());
	                logger.info(" 扫描到 自定义注解 :" + data.value() );
	            }
	        } catch (Exception e) {
	            logger.error(String.format("Choose DataSource error, method:%s, msg:%s", methodName, e.getMessage()));
	        }
	}

	
	@After("aspect()")
	public void doAfter(JoinPoint joinPoint) {

		 DynamicDataSourceHolder.clearDataSource();

	}
}
